<template>
  <div class="primaryClassification">
    <div class="btnGrounp">
      <el-button @click="handleEdit(0)">新增一级分类</el-button>
    </div>
    <div class="search">
      <ul>
        <li>
          <span>一级分类</span>
          <el-input v-model="search.classLevel1" placeholder="请输入内容" @keyup.enter.native="searchClassOne"></el-input>
        </li>
        <li class="lastLi">
          <el-button @click="searchClassOne">查询</el-button>
        </li>
      </ul>
    </div>
    <div class="content">
       <el-table :data="contentData" style="width: 100%" stripe :header-cell-class-name='lastTaHead'>
        <el-table-column prop="sort" label="排序" width="20%"  align='center'></el-table-column>
        <!-- <el-table-column prop="icon" label="图标" width="20%"  align='center'></el-table-column> -->
        <el-table-column label="图标" width="20%" align='center'>
          <template slot-scope="scope">
            <img :src="scope.row.icon" alt="">
          </template>
        </el-table-column>
        <el-table-column prop="chinaName" label="一级分类" width="20%" align='center' ></el-table-column>
        <el-table-column label="操作" align='center' width="100%" class-name='lastTd'>
          <template slot-scope="scope">
            <el-button class="edit" size='mini'  @click="handleEdit(1,scope.$index, scope.row)">编辑</el-button>
            <el-button  class="delete" size='mini' type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            <el-button :class="{'adjust':true}" v-if="scope.row.showAdjust"  size='mini' @click="handleAdjust(scope.$index, scope.row)"  >调整排序</el-button>
            <div :class="{'adjustSort':true}"  v-else>
              <el-input v-model="scope.row.adjustValue" placeholder="请输入内容" @keyup.enter.native="sureAdjust(scope.row.id,scope.row)"></el-input> <el-button class="defaultBtn" @click="sureAdjust(scope.row.id,scope.row)" >确定</el-button>
            </div>
          </template>
        </el-table-column >
      </el-table>
    </div>
    <!-- 弹框 -->
    <div class="dialog">
      <el-dialog :title="formTitle" :visible.sync="dialogFormVisible">
        <el-form :model="form">
          <el-form-item label="图标" label-width="7.5rem">
            <!-- :data="upLoadData" -->
            <el-upload class="avatar-uploader" action="111"   :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img v-if="form.icon" :src="form.icon" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <div class="tips" v-if="isAdd">
              <span>W：275像素</span><br>
              <span>H：230像素</span>           
            </div>
          </el-form-item>
          <el-form-item label="中文" label-width="7.5rem">
            <el-input v-model="form.chinaName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="英文" label-width="7.5rem">
            <el-input v-model="form.englishName" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="primaryClass">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div class="paging">
      <el-pagination :page-size="pageSize"  layout="prev, pager, next" :total="totalNum" @current-change='changeCurrentPage'></el-pagination>
    </div>
  </div>
</template>

<script>
export default {
  name: 'primaryClassification',
  data () {
    return {
      search:{
        classLevel1:'',//一级分类
      },//查询对象
      //内容数据
      contentData: [],
      pageSize:7,//每页显示条目个数
      totalNum:1000,//总条目数   
      currentPage:1,
      formTitle: '编辑',//表单标题
      dialogFormVisible:false,//对话框是否可见
      //对话框表单
      form: {
          chinaName: '',
          englishName: '',
          icon:"",
          iconKey:"",
        },
      id:"",//操作某一行的id
      isAdd:true,//新增显示图片tips
    }
  },
  methods: {
    //编辑行
    handleEdit(type,index, row) {
      let _this = this;
      //console.log(type,index, row);
      _this.dialogFormVisible = true;//显示对话框

      if(type == 0){//新增操作
        _this.formTitle = '新增';
        _this.form.chinaName = '';
        _this.form.englishName = '';
        _this.form.icon = '';
        _this.form.iconKey = '';

        _this.isAdd = true;//新增显示图片tips
      }else{//编辑操作
        _this.formTitle = '编辑';
        _this.id = row.id;
        _this.form.icon = row.icon;
        _this.form.chinaName = row.chinaName;
        _this.form.englishName = row.englishName;

        _this.isAdd = true;//编辑显示图片tips

      }

    },
    //删除行
    handleDelete(index, row) {
      let _this = this;
      //console.log(index, row);
      _this.$confirm('是否删除?',  {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let api = '/api/sysClassOne/delete?id='+row.id;
          let sessionId = _this.$store.state.id;
          _this.axios({
            url:api,
            method: 'post',
            headers:{
              sessionId,
            }		
          }).then(res=>{
            //console.log('删除行',res)
            if(res.data.code == 401){
                _this.$message({
                  type: 'info',
                  message: '登录已失效，请重新登录'
                });  
                _this.$router.push({
                  path:"/"
                });
                return
            }
            if(res.data.code == 500){
            _this.$message(res.data.data.errMsg);
            return
          }
            if(res.data.code == 200){
              _this.$message({
                type: 'success',
                message: '删除成功!'
              });
              _this.getAllPrimary();//刷新
            }
          });
        }).catch(() => {
          _this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    //调整排序
    handleAdjust(index, row) {
      let _this = this;
      //注意showAdjust是数组每一个对象元素添加属性，层次[{}]太深,且不是vue实例化时指定，所以出现了数据更改，
      //页面没有热响应的情况，需要用$set方法修改媒体{}的showAdjust属性，且用数组的splice热响应监听方法对
      //数组进行修改
      // _this.$set(row, 'showAdjust', false)
      // _this.contentData.splice(index, 1, row);
      // debugger
      _this.contentData.forEach((item,indexs)=>{
        //console.log(indexs, item);
        if(indexs == index){
          _this.$set(item, 'showAdjust', false)
          
        }else{
           _this.$set(item, 'showAdjust', true)
        }
        _this.contentData.splice(indexs, 1, item);

      });
      // _this.$forceUpdate();//强制刷新
      //console.log(index, row,_this.contentData);


    },
    //确定调整
    sureAdjust(id,row){
      let _this = this;
      let sessionId = _this.$store.state.id;
      let api = '/api/sysClassOne/changeSort?id='+id+'&sort='+row.adjustValue;
      _this.axios({
          url:api,
          method: 'post',
          headers:{
            sessionId,
          }		
        }).then(res=>{
        //console.log('确认修改顺序',res);
        if(res.data.code == 401){
            _this.$message({
              type: 'info',
              message: '登录已失效，请重新登录'
            });  
            _this.$router.push({
              path:"/"
            });
            return
          }
          if(res.data.code == 200){
            _this.$message({
              type: 'success',
              message: '修改成功！'
            }); 
            _this.getAllPrimary();//刷新
          }
      });
    },
    //改变当前页
    changeCurrentPage(val){
      //console.log(`当前页: ${val}`);
      let _this = this;
      _this.currentPage = val;
      _this.getAllPrimary();//调用同一接口
    },
    //最后一列的表头
    lastTaHead({row, column, rowIndex, columnIndex}){
      let _this = this;
      if(columnIndex == 3){
        return 'lastTd lastTdHead'
      }
    },
    //获取所有一级分类信息
    getAllPrimary(searchPage){
      let _this = this;
      // debugger
      let sessionId = _this.$store.state.id;//获取token
      let api = '/api/sysClassOne/find_page';
      _this.axios.post(api,{
        "chinaNameLike": _this.search.classLevel1,
        // "englishNameLike": _this.form.englishName,
        "pageIndex": searchPage == 1?searchPage:_this.currentPage,
        "pageSize": 7
      },{
        headers:{
          sessionId,
        },
      }).then(res=>{
        _this.totalNum = res.data.data.count;//获取总条数
        _this.contentData = res.data.data.bussData;
        _this.contentData.forEach(item=>{
          item.showAdjust = true;
        });
        //console.log('所有一级分类',_this.contentData,'res',res);

      });
    },
    //查询一级分类
    searchClassOne(){
      let _this = this;
      _this.getAllPrimary(1);//调用同一接口
    },
    //操作一级分类
    primaryClass(){
      let _this = this;
      if(_this.form.chinaName == ''){
        _this.$message('请先输入中文名');
        return
      }
      if(_this.form.englishName == ''){
        _this.$message('请先输入英文名');
        return
      }
      let reg = /^[a-zA-Z]+$/;
      if(!reg.test(_this.form.englishName.replace(/\s+/g,""))){
        _this.$message('请确认输入英文名字');
        return
      }
      let api = '';
      let data = '';//传参
      if(_this.formTitle == '新增'){
        api = '/api/sysClassOne/insert';
        data = {
          "chinaName": _this.form.chinaName,
          "englishName": _this.form.englishName,
          "icon": _this.form.iconKey,
        };
        
      }else{//编辑
        api = '/api/sysClassOne/update';
        data = {
            "chinaName": _this.form.chinaName,
            "englishName": _this.form.englishName,
            "icon": _this.form.iconKey,
            "id": _this.id,
        }
      }
      let sessionId = _this.$store.state.id;
      _this.axios.post(api,data,{
        headers:{
            sessionId,
          }
      }).then(res=>{
          //console.log('操作一级分类',res);
          if(res.data.code == 401){
            _this.$message({
              type: 'info',
              message: '登录已失效，请重新登录'
            });  
            _this.$router.push({
              path:"/"
            });
            return
          }
          if(res.data.code == 200){
            _this.$message({
              type: 'success',
              message: _this.formTitle+'成功！'
            }); 
            _this.form.chinaName = '';//清空字段
            _this.form.englishName = '';//清空字段
            _this.dialogFormVisible = false;//隐藏弹框
            _this.getAllPrimary();//刷新
          }
        });
      
    },
    //图片上传成功实现本地预览
    handleAvatarSuccess(res, file) {
      let _this = this;
      _this.form.icon = URL.createObjectURL(file.raw);
    },
    //上传之前的钩子函数
    beforeAvatarUpload(file) {
      //console.log('上传文件',file);
      let _this = this;
      
      let sessionId = _this.$store.state.id;//获取token

      let suffix = file.name.split('.')[1];
      //console.log(suffix,'suffix');
      let contentType = file.type;
      //console.log('contentType',contentType);
      if(contentType.indexOf('image')<0){
          _this.$message('请上传图片');
          return
        }
      let api = '/api/base/app/getOSSUploadFormData/'+suffix;
      _this.axios.get(api,{
            // params:fd,
            headers:{
              sessionId,
            }
        })
      .then(function (res) {      
          //console.log('第二步上传文件',res);
          if(res.data.code == 401){
            _this.$message({
              type: 'info',
              message: '登录已失效，请重新登录'
            });  
            _this.$router.push({
              path:"/"
            });
            return
          }
          let key = res.data.data.bussData.fileKey;
          // _this.form.iconKey = res.data.data.bussData.fileKey;
          // _this.form.icon  = res.data.data.bussData.downloadUrl;
          let uploadUrl = res.data.data.bussData.uploadUrl;
          let downloadUrl = res.data.data.bussData.downloadUrl;
          let uploadFormData = res.data.data.bussData.formData;
          // // let api2 = res.data.data.bussData.downloadUrl+'?fileKey='+_this.form.iconKey;
          // // // let api2 =  _this.form.icon  = res.data.data.bussData.downloadUrl;
          // // //console.log('api2',api2);
          let fd = new FormData();
          fd.append('OSSAccessKeyId',uploadFormData.OSSAccessKeyId);//传文件
          fd.append('signature',uploadFormData.signature);//传文件
          fd.append('success_action_status',uploadFormData.success_action_status);//传文件
          fd.append('key',uploadFormData.key);//传文件
          fd.append('policy',uploadFormData.policy);//传文件
          fd.append('file',file);//传文件
          _this.axios.post(uploadUrl,fd).then(res=>{
            //console.log('第二步上传res',res);
            if(res.status == 200){
              //console.log('第二步上传成功');
              _this.form.icon  = downloadUrl;
              _this.form.iconKey = key;
            }else{
              _this.$message({
                type: 'info',
                message: '上传失败，请重新上传'
              });  
            }
          }).catch(err=>{
            //console.log('第二步上传错误',err);
            _this.form.icon  = downloadUrl;
            _this.form.iconKey = key;
            
          });
      })
      return false//屏蔽了action的默认上传
    },
  },
  mounted(){
    let _this = this;
    _this.getAllPrimary();//获取所有一级分类
  }
}
</script>

<style scoped>
/* 整体样式 */
.primaryClassification{
  height: 100%;
  width: 100%;
  position: relative;
  padding-left: 2%;
}
.primaryClassification>>>.btnGrounp .el-button{
  background-color: rgba(53, 174, 160, 1);
  color: rgb(255, 255, 255,1);
}
/* 隐藏 */
.primaryClassification>>>.hid{
  display: none !important;
}
/* 查询 */
.primaryClassification>>>.search{
  width: 100%;
  height: 10%;
  line-height: 10%;
  position: absolute;
  top: 10%;
  font-size: .875rem;
}
/* 输入框 */
.primaryClassification>>>.el-input,.el-select{
  width: 70%;
}
/* 选择框下的输入框 */
/* .primaryClassification>>>.el-select .el-input{
  width: 100%;
} */
.primaryClassification>>>.search ul{
  width: 100%;
  height: 100%;
  display: flex;
  
}
.primaryClassification>>>.search ul li{
  /* flex:1; */
  padding-right: 1%;
}
.primaryClassification>>>.search ul li.lastLi{
    position:absolute;
    right: 15%;
}
.primaryClassification>>>.search ul li span{
  padding-right: 2%;
}
.primaryClassification>>>.search ul li.lastLi button{
  color:rgba(16, 16, 16, 1);
}
/* 主要内容 */
.primaryClassification>>>.content{
  width: 85%;
  position: absolute;
  top: 21%;
  color: rgba(16, 16, 16, 1) !important;
}
.primaryClassification>>>.content img{
  width: 21%;
}
.primaryClassification>>>.content table{
  width: 100% !important;
}
/* table无数据时的显示 */
.primaryClassification>>>.el-table__empty-block{
   width: 100% !important;
}
/* 最后一列 */
.primaryClassification>>>.lastTd{
  text-align: left;
  padding-left: 2%;
}
/* 消除表头变形 */
.primaryClassification>>>table .gutter{
  display: block !important;
}
.primaryClassification>>>.lastTd .cell{
   height: 1.75rem;
  line-height: 1.75rem;

}
/* .primaryClassification>>>.lastTd .cell{
  height: 20%;
  line-height: 20%;
} */
/* 最后一列表头 */
.primaryClassification>>>.lastTdHead{
  padding-left: 9%;
}
/* 表格内的按钮 */
.primaryClassification>>>.content table .defaultBtn{
  color: rgba(16, 16, 16, 1);
}
/* 编辑按钮 */
.primaryClassification>>>.edit{
  background-color: rgba(63, 81, 181, 1);
}
/* 删除按钮 */
.primaryClassification>>>.delete{
  background-color: rgba(229, 28, 35, 1);
}
/* 调整排序按钮 */
.primaryClassification>>>.adjust{
  background-color: rgba(139, 195, 74, 1);

}
/* 调整排序输入框 */
.primaryClassification>>>.adjustSort{
  display: inline-block;
  height: 97%;
}
.primaryClassification>>>.adjustSort .el-input{
  width: 42%;
  height: 100%;

}
.primaryClassification>>>.adjustSort .el-input input{
  height: 100%;
}
.primaryClassification>>>.adjustSort .el-input__inner{
  /* height: 1.9375rem; */
}
.primaryClassification>>>.adjustSort .el-button{
  line-height: 0.1;
  /* height: 100%;
  line-height: 1.75rem; */

}
/* 对话框 */
.primaryClassification>>>.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .primaryClassification>>>.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .primaryClassification>>>.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .primaryClassification>>>.avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  /* 弹框图片tips */
  .primaryClassification>>>.tips{
    position: absolute;
    top: 20%;
    left: 37%;
  }
/* 分页 */
.primaryClassification>>>.paging{
  position: absolute;
  bottom: 0%;
  text-align: center;
  width: 85%;
}

</style>
